package com.scott.utils;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;

public class ZooKeeperConnectionUtil {


    private static final String NAMESPACE = "huanghoulin";
    private static final String CONNECT_STRING = "192.168.235.128:2181";
    private static final int DEFAULT_SESSION_TIMEOUT_MS = Integer.getInteger("curator-default-session-timeout", 60 * 1000);
    private static final int DEFAULT_CONNECTION_TIMEOUT_MS = Integer.getInteger("curator-default-connection-timeout", 15 * 1000);


    public static CuratorFramework getConnectionSimple() {
        RetryPolicy retryPolicy = new RetryOneTime(5 * 1000);
        CuratorFramework connection = CuratorFrameworkFactory.newClient(CONNECT_STRING, DEFAULT_SESSION_TIMEOUT_MS, DEFAULT_CONNECTION_TIMEOUT_MS, retryPolicy);
        connection.start();
        return connection;
    }

    public static void closeConnection(CuratorFramework connection) {
        if (null != connection) {
            connection.close();
        }
    }

    public static CuratorFramework getConnectionBeginWithNamespace() {
        RetryPolicy retryPolicy = new RetryOneTime(5 * 1000);
        CuratorFramework connection = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_STRING)
                .sessionTimeoutMs(DEFAULT_SESSION_TIMEOUT_MS)
                .connectionTimeoutMs(DEFAULT_CONNECTION_TIMEOUT_MS)
                .retryPolicy(retryPolicy)
                .namespace(NAMESPACE)
                .build();
        connection.start();
        return connection;
    }
}
